<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>事件列表</h3>
          <el-button type="primary" @click="showCreateEventDialog">新建事件</el-button>
        </div>
      </template>
      
      <el-form :inline="true" class="search-form">
        <el-form-item label="事件名称">
          <el-input v-model="searchForm.name" placeholder="请输入事件名称" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="选择分类" clearable style="width: 180px;">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="filteredEvents" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="事件名称" />
        <el-table-column prop="category" label="分类" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="nodeCount" label="节点数量" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="320">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewEventDetail(row.id)">详情</el-button>
            <el-button type="success" size="small" @click="runEvent(row.id)">运行</el-button>
            <el-button type="warning" size="small" @click="viewEventLogs(row.id)">日志</el-button>
            <el-button type="danger" size="small" @click="confirmDeleteEvent(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建事件弹窗 -->
    <el-dialog
      v-model="createEventDialogVisible"
      title="新建事件"
      width="500px"
    >
      <el-form :model="eventForm" label-width="80px" ref="eventFormRef" :rules="eventRules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="eventForm.name" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="eventForm.categoryId" placeholder="选择分类" style="width: 100%">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="eventForm.description" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createEventDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createEvent" :loading="submitting">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const store = useStore()
const router = useRouter()

const loading = ref(false)
const submitting = ref(false)
const createEventDialogVisible = ref(false)
const eventFormRef = ref(null)

const searchForm = ref({
  name: '',
  categoryId: ''
})

const eventForm = ref({
  name: '',
  categoryId: '',
  description: '',
  nodes: []
})

const eventRules = {
  name: [{ required: true, message: '请输入事件名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }]
}

const categories = computed(() => store.state.categories)

const events = computed(() => {
  return store.state.events.map(event => {
    const category = store.getters.getCategoryById(event.categoryId)
    return {
      ...event,
      category: category ? category.name : '未分类',
      nodeCount: event.nodes ? event.nodes.length : 0
    }
  })
})

const filteredEvents = computed(() => {
  return events.value.filter(event => {
    const nameMatch = searchForm.value.name ? event.name.includes(searchForm.value.name) : true
    const categoryMatch = searchForm.value.categoryId ? event.categoryId === searchForm.value.categoryId : true
    return nameMatch && categoryMatch
  })
})

const showCreateEventDialog = () => {
  createEventDialogVisible.value = true
  eventForm.value = {
    name: '',
    categoryId: '',
    description: '',
    nodes: []
  }
}

const createEvent = async () => {
  if (!eventFormRef.value) return
  
  await eventFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const newEvent = {
          ...eventForm.value,
          id: `event_${Date.now()}`,
          createTime: new Date().toLocaleString(),
          nodes: []
        }
        await store.dispatch('createEvent', newEvent)
        ElMessage.success('创建事件成功')
        createEventDialogVisible.value = false
      } catch (error) {
        ElMessage.error('创建事件失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const viewEventDetail = (id) => {
  router.push(`/events/${id}`)
}

const runEvent = (id) => {
  router.push(`/events/${id}/run`)
}

const viewEventLogs = (id) => {
  router.push(`/events/${id}/logs`)
}

const confirmDeleteEvent = (id) => {
  ElMessageBox.confirm('确认删除该事件？此操作不可恢复！', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await store.dispatch('deleteEvent', id)
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const resetSearch = () => {
  searchForm.value = {
    name: '',
    categoryId: ''
  }
}

onMounted(async () => {
  loading.value = true
  try {
    await store.dispatch('fetchEvents')
    await store.dispatch('fetchCategories')
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
</style> 